<template>
  <div class="table-container">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="餐桌编号">
          <el-input v-model="searchForm.tableNumber" placeholder="请输入餐桌编号" clearable />
        </el-form-item>
        <el-form-item label="所属餐厅">
          <el-select style="width: 150px" v-model="searchForm.restaurantId" placeholder="请选择餐厅" clearable>
            <el-option
              v-for="item in restaurants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select style="width: 150px" v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="空闲" :value="0" />
            <el-option label="已预订" :value="1" />
            <el-option label="使用中" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增餐桌</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="tableNumber" label="餐桌编号" />
        <el-table-column prop="restaurantName" label="所属餐厅" />
        <el-table-column prop="capacity" label="可容纳人数" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              :type="scope.row.status === 0 ? 'warning' : 'success'"
              size="small"
              :disabled="scope.row.status === 1"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 0 ? '设为使用中' : '设为空闲' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              :disabled="scope.row.status !== 0"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="餐桌编号" prop="tableNumber">
          <el-input v-model="form.tableNumber" placeholder="请输入餐桌编号" />
        </el-form-item>
        <el-form-item label="所属餐厅" prop="restaurantId">
          <el-select v-model="form.restaurantId" placeholder="请选择餐厅">
            <el-option
              v-for="item in restaurants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可容纳人数" prop="capacity">
          <el-input-number v-model="form.capacity" :min="1" :max="20" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 搜索表单数据
const searchForm = reactive({
  tableNumber: '',
  restaurantId: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 餐厅列表
const restaurants = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  id: '',
  tableNumber: '',
  restaurantId: '',
  capacity: 4,
  status: 0
})

// 表单验证规则
const rules = {
  tableNumber: [
    { required: true, message: '请输入餐桌编号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  restaurantId: [
    { required: true, message: '请选择所属餐厅', trigger: 'change' }
  ],
  capacity: [
    { required: true, message: '请输入可容纳人数', trigger: 'blur' }
  ]
}

// 获取餐厅列表
const getRestaurants = async () => {
  try {
    const { data } = await axios.get('/api/restaurant/list/all')
    restaurants.value = data.data
  } catch (error) {
    console.error('获取餐厅列表失败:', error)
  }
}

// 获取餐桌列表
const getList = async () => {
  try {
    const response = await axios.get('/api/dining/table/page', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        tableNumber: searchForm.tableNumber,
        restaurantId: searchForm.restaurantId,
        status: searchForm.status
      }
    })
    const { records, total: totalCount } = response.data.data
    tableData.value = records
    total.value = totalCount
  } catch (error) {
    console.error('获取餐桌列表失败:', error)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'success'
    case 1: return 'warning'
    case 2: return 'info'
    default: return ''
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '空闲'
    case 1: return '已预订'
    case 2: return '使用中'
    default: return '未知'
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.tableNumber = ''
  searchForm.restaurantId = ''
  searchForm.status = ''
  handleSearch()
}

// 新增餐桌
const handleAdd = () => {
  dialogTitle.value = '新增餐桌'
  dialogVisible.value = true
  Object.assign(form, {
    id: '',
    tableNumber: '',
    restaurantId: '',
    capacity: 4,
    status: 0
  })
}

// 编辑餐桌
const handleEdit = (row) => {
  dialogTitle.value = '编辑餐桌'
  dialogVisible.value = true
  Object.assign(form, row)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await axios.put('/api/dining/table', form)
        } else {
          await axios.post('/api/dining/table', form)
        }
        ElMessage.success('保存成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  })
}

// 更改状态
const handleStatusChange = async (row) => {
  const newStatus = row.status === 0 ? 2 : 0
  try {
    await axios.put(`/api/dining/table/status/${row.id}/${newStatus}`)
    ElMessage.success('状态更新成功')
    getList()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 删除餐桌
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该餐桌吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/dining/table/${row.id}`)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}


onMounted(() => {
  getRestaurants()
  getList()
})
</script>

<style scoped>
.table-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
